package model

import (
	"errors"
	"time"
)

type Paper struct {
	Id         int64
	MinLevel   int32 // user level limit
	Name       string
	Enable     bool
	Group      string
	CreatedAt  time.Time `xorm:"created"`
	UpdatedAt  time.Time `xorm:"updated"`
	TotalScore int32
	PassScore  int32
	AvgScore   int32 // average score for user
	Duration   int32
	Describe   string
	Sids       []int64
}

func (p *Paper) OneById() error {
	ok, err := orm.ID(p.Id).Get(p)
	if !ok {
		return errors.New(PaperNotFound)
	}
	return err
}

func (p *Paper) CheckEnable() error {
	if !p.Enable {
		return errors.New(PaperDisabled)
	}
	return nil
}

func (p *Paper) Page(num, size int32, desc bool, order, nameLike string) ([]Paper, error) {
	length := int(size)
	start := (int(num) - 1) * length
	if length == 0 {
		length = 5
	}
	var papers []Paper
	o := orm.Where("enable = ?", true).Limit(length, start)
	if order == "" {
		order = "id"
	}
	if nameLike != "" {
		o.And("name LIKE ?", "%"+nameLike+"%")
	}
	if desc {
		o.Desc(order)
	} else {
		o.Asc(order)
	}
	err := o.Find(&papers)
	return papers, err
}

func (p *Paper) CountAll() (int64, error) {
	return orm.Count(p)
}

func (p *Paper) Count() (int64, error) {
	return orm.Where("enable = ?", true).Count(p)
}

func (p *Paper) CountBy(nameLike string) (int64, error) {
	o := orm.Where("enable = ?", true)
	if nameLike != "" {
		o.And("name LIKE ?", "%"+nameLike+"%")
	}
	return o.Count(p)
}

func (p *Paper) Create() error {
	p.Enable = true
	ok, err := orm.Insert(p)
	if ok == 0 {
		return errors.New(PaperCreateFailed)
	}
	return err
}

func (p *Paper) AddSection(sid int64) error {
	p.Sids = append(p.Sids, sid)
	ok, err := orm.ID(p.Id).Cols("sids").Update(p)
	if ok == 0 {
		return errors.New(PaperUpdateFailed)
	}
	return err
}
